<!-- 文件列表-component -->
<template>
  <OptionBoard
    :isOpen="isOptionBoardOpen"
    :options="options"
    :x="position.x"
    :y="position.y"
    @close="optionBoardCloseHandle"
  />
  <div class="flex items-center mb-2 pl-4" v-if="fileStore.visible">
    <Checkbox
      v-model="checked"
      binary
      variant="filled"
      @change="selectAll"
      inputId="ingredient"
    />
    <label for="ingredient" class="ml-2">{{
      i18nStore.translate('select_all')
    }}</label>
  </div>
  <div
    v-show="!flagStore.isFileListSpinnerShow"
    class="flex space-x-3 min-h-[85vh] mobile:space-x-0 mobile:p-2 mobile:min-h-screen lg:overflow-hidden mobile:flex-wrap-reverse mobile:overflow-hidden bg-white dark:bg-dark-background"
    @contextmenu.prevent="showOptions"
  >
    <div
      class="relative w-full"
      v-if="fileStore.curFileList.length + fileStore.curFolderList.length"
    >
      <div
        ref="container"
        :class="[
          'px-4',
          'mobile:px-0',
          'lg:h-full',
          'lg:w-full',
          'lg:overflow-y-auto',
          'lg:px-0',
          'overflow-x-hidden',
          'mobile:overflow-y-hidden',
          { 'grid-view-sidebar': fileStore.isGridironPlan }
        ]"
      >
        <div
          v-for="(item, index) in renderList"
          :key="
            item.file_id ? `file-${item.file_id}` : `folder-${item.folder_id}`
          "
          @contextmenu.prevent.stop="showOptions($event, item)"
          @dblclick="dblClickHandle(item)"
        >
          <!-- @click="dblClickHandle(item)" -->
          <div
            v-if="!fileStore.isGridironPlan"
            draggable="true"
            spellcheck="false"
            :class="isSelected(item)"
            @click="selectFile(item)"
            class="flex mobile:flex-wrap px-2.5 py-2 select-none items-center rounded-xl border-2 border-dashed border-transparent hover:bg-light-background dark:hover:bg-dark-foreground"
          >
            <Checkbox
              v-if="fileStore.visible"
              v-model="fileStore.delFilesList"
              name="pizza"
              :value="item"
              class="mr-2"
              @change.stop="checkeds"
            />
            <div class="relative w-16 shrink-0">
              <div v-if="item.type === 'folder'" class="svg-color-theme">
                <SvgIcon
                  name="folder"
                  :style="{ width: '53px', height: '52px' }"
                  iconClass="svg-color-theme"
                />
              </div>
              <div
                v-else-if="item.type === 'image'"
                class="relative w-16 shrink-0"
              >
                <img
                  :src="item.url"
                  alt=""
                  loading="lazy"
                  class="ml-0.5 h-12 w-12 rounded object-cover"
                />
              </div>
              <div
                v-else-if="item.fileType.type === 'video'"
                class="relative w-16 shrink-0"
              >
                <video
                  :src="item.url"
                  class="ml-0.5 h-12 w-12 object-cover rounded"
                  loop
                  muted
                  @loadeddata="
                    (e) => {
                      e.target.volume = 0;
                      e.target.play();
                    }
                  "
                />
              </div>
              <div v-else class="flex items-center justify-center pr-2">
                <span
                  class="text-theme-color absolute z-[5] mx-auto mt-1 inline-block w-7 overflow-hidden text-ellipsis text-center text-[9px] font-semibold"
                >
                  {{ item.type }}
                </span>
                <SvgIcon
                  name="file"
                  svgClass="vue-feather dark:text-gray-800 text-gray-100 "
                  :style="{ width: '38px', height: '51px' }"
                  iconClass="svg-color-theme"
                />
              </div>
            </div>
            <div class="pl-2">
              <span
                :title="item.name"
                contenteditable="false"
                class="mb-0.5 block overflow-hidden text-ellipsis whitespace-nowrap text-sm font-bold hover:underline"
                style="max-width: 200px"
              >
                {{ item.name }}
              </span>
              <div class="flex items-center">
                <small class="block text-xs text-gray-500 dark:text-gray-500">
                  <!-- <span v-if="item.type === 'folder'"
                    >{{ item.items + i18nStore.translate('items') }},</span
                  > -->
                  <span>{{ item.size }}</span>
                  <i
                    v-if="item[FILE_LIST.FILE_SHARE]"
                    class="pi pi-link vue-feather text-theme-color text-xs"
                  />
                  <span>{{ item.size }}</span>
                  {{ i18nStore.translate('date', item.times) }}
                </small>
              </div>
            </div>
          </div>
          <div
            v-else
            draggable="true"
            spellcheck="false"
            class="relative z-0 flex mobile:h-56 h-48 select-none flex-wrap items-center justify-center rounded-lg border-2 border-dashed border-transparent px-1 pt-2 text-center sm:h-56 lg:h-60 dark:hover:bg-dark-foreground lg:hover:bg-light-background"
            :class="isSelected(item)"
            highlight="true"
            @click="selectFile(item)"
          >
            <div class="w-full">
              <div class="relative mx-auto">
                <div
                  v-if="item.type === 'folder'"
                  class="mt-3 mb-5 inline-block scale-150 transform lg:mt-2 lg:mb-8"
                >
                  <div class="svg-color-theme">
                    <SvgIcon
                      name="folder"
                      :style="{ width: '53px', height: '52px' }"
                      iconClass="svg-color-theme"
                    />
                  </div>
                </div>

                <div
                  v-else-if="item.type === 'image'"
                  class="relative mb-4 inline-block h-24 w-28 lg:h-28 lg:w-36"
                >
                  <img
                    :src="item.url"
                    alt=""
                    loading="lazy"
                    class="h-full w-full rounded-lg object-cover shadow-lg"
                  />
                </div>
                <div
                  v-else-if="item.fileType.type === 'video'"
                  class="relative mb-4 inline-block h-24 w-28 lg:h-28 lg:w-36"
                >
                  <video
                    :src="item.url"
                    class="h-full w-full rounded-lg object-cover shadow-lg"
                    loop
                    muted
                    @loadeddata="
                      (e) => {
                        e.target.volume = 0;
                        e.target.play();
                      }
                    "
                  />
                </div>
                <div
                  v-else
                  class="flex items-center justify-center z-0 mt-5 mb-10 scale-125 transform lg:mb-12 lg:mt-6 lg:scale-150"
                >
                  <span
                    class="text-theme-color absolute z-[5] mx-auto mt-1 inline-block w-7 overflow-hidden text-ellipsis text-center text-[9px] font-semibold"
                  >
                    {{ item.type }}
                  </span>
                  <SvgIcon
                    name="file"
                    svgClass="vue-feather dark:text-gray-800 text-gray-100 "
                    :style="{ width: '38px', height: '51px' }"
                    iconClass="svg-color-theme"
                  />
                </div>
              </div>
              <div class="text-center relative">
                <span
                  :title="item.name"
                  contenteditable="false"
                  class="inline-block w-full overflow-hidden text-ellipsis whitespace-nowrap text-sm font-bold leading-5 tracking-tight md:px-6 hover:underline"
                >
                  {{ item.name }}
                </span>
                <div class="flex items-center justify-center">
                  <small class="block text-xs text-gray-500 dark:text-gray-500">
                    <!-- {{
                      item.type === 'folder'
                        ? item.items + ' ' + i18nStore.translate('items')
                        : item.size
                    }} -->
                    <p>{{ item.size }}</p>
                    <i
                      v-if="item[FILE_LIST.FILE_SHARE]"
                      class="pi pi-link vue-feather text-theme-color text-xs"
                    />
                    <span
                      class="text-xs text-gray-500 dark:text-gray-500 lg:inline-block"
                      >{{ i18nStore.translate('date', item.times) }}</span
                    >
                  </small>
                </div>
                <Checkbox
                  v-if="fileStore.visible"
                  v-model="fileStore.delFilesList"
                  name="pizza"
                  :value="item"
                  @change.stop="checkeds"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 无文件时显示上传文件 -->
    <div
      v-if="fileStore.curFileList.length + fileStore.curFolderList.length === 0"
      class="relative w-full h-screen flex items-center justify-center"
      ref="container"
    >
      <div class="flex items-center justify-center md:px-0 px-4">
        <div class="text-content text-center">
          <h1 class="title">{{ i18nStore.translate('upload_title') }}</h1>
          <p class="description">
            {{ i18nStore.translate('upload_description') }}
          </p>
          <FileUpload
            mode="basic"
            name="demo[]"
            :chooseLabel="i18nStore.translate('upload_label')"
            auto
            customUpload
            @uploader="onUploader"
            :pt="{ label: { style: { fontWeight: 'bold' } } }"
          >
            <template #uploadicon>
              <span></span>
            </template>
          </FileUpload>
        </div>
      </div>
    </div>
    <!-- 分享模式时无分享列表时显示 -->
    <div
      v-if="mode === 'share' && fileStore.curShareList.length === 0"
      class="flex items-center justify-center fixed top-0 bottom-0 -left-20 right-0 md:px-0 px-4"
    >
      <div class="text-content text-center">
        <h1 class="title dark:text-white">
          {{ i18nStore.translate('not_shared_anything') }}
        </h1>
      </div>
    </div>

    <InfoBoard
      v-if="flagStore.isInfoBoardOpen"
      :fileInfo="fileStore.curFileInfo"
      :curFolder="fileStore.curFolderInfo"
    />
  </div>
  <div
    v-if="flagStore.isFileListSpinnerShow"
    class="flex items-center justify-center h-screen"
  >
    <ProgressSpinner
      style="width: 40px; height: 40px"
      strokeWidth="4"
      animationDuration=".5s"
      :pt="{
        circle: {
          class: 'stroke-theme-color',
          style: {
            animation: 'p-progress-spinner-dash 1.5s ease-in-out infinite'
          }
        }
      }"
    />
  </div>
  <div class="mobile:fixed mobile:bottom-2 mobile:left-2 flex">
    <MyButton
      v-if="fileStore.visible"
      class="py-1 px-3 bg-[#00e0a9] rounded-lg text-white"
      @click="deleteAll"
    >
      {{ i18nStore.translate('delete_selected') }}
    </MyButton>
    <MyButton
      v-if="fileStore.visible && path === '/trash'"
      class="py-1 px-3 bg-[#00e0a9] rounded-lg text-white ml-3"
      @click="recover"
    >
      {{ i18nStore.translate('recovery_selected') }}
    </MyButton>
  </div>
</template>

<script setup>
import {
  useFlagStore,
  useI18nStore,
  useFileStore,
  useToastStore,
  useUserInfoStore
} from '@/stores';
import { FILE_LIST } from './filedsConfig';
import { getFileType, formatFileSize } from '@/utils';
import { upload } from '@/apis/upload';
const toastStore = useToastStore();
const i18nStore = useI18nStore();
const flagStore = useFlagStore();
const fileStore = useFileStore();
const container = ref(null);
const route = useRoute();
const userInfoStore = useUserInfoStore();

const { path } = route;

const isOptionBoardOpen = ref(false);
const options = ref([{ type: 'delete', content: 'delete' }]);
const position = ref({ x: 0, y: 0 });

const props = defineProps({
  mode: {
    type: String,
    default: 'file'
  }
});
const showOptions = (e, item) => {
  isOptionBoardOpen.value = true;
  position.value = { x: e.clientX, y: e.clientY };
  if (item) {
    fileStore.setCurFileInfo(item);
    if (fileStore.type === 'trash') {
      options.value = [
        { type: 'map', content: 'recovery', file: item },
        { type: 'times-circle', content: 'delete_forever', file: item }
      ];
    } else {
      if (fileStore.checkIsFolder(item)) {
        options.value = [
          { type: 'trash', content: 'delete', file: item }
          // { type: 'eye', content: 'detail', file: item }
          // { type: 'cloud-download', content: 'download', file: item }
        ];
      } else if (fileStore.checkIsFile(item)) {
        options.value = [
          // { type: 'trash', content: 'delete', file: item },
          {
            type: 'link',
            content: fileStore.curFileInfo.share ? 'edit_share' : 'share',
            file: item
          },
          // { type: 'eye', content: 'detail', file: item },
          { type: 'cloud-download', content: 'download', file: item }
        ];
        if (path === '/myFiles' || path === '/mySmallfiles')
          options.value.push({ type: 'trash', content: 'delete', file: item });
      }
    }
  } else {
    const { path } = route;
    if (props.mode === 'share') {
      options.value = [];
      isOptionBoardOpen.value = false;
      return;
    }
    if (props.mode === 'papelera') {
      options.value = [];
      isOptionBoardOpen.value = false;
      return;
    }
    if (path === '/myFiles') {
      options.value = [
        {
          type: 'upload',
          content: 'upload_files',
          icon: {}
        },
        {
          type: 'folder-open',
          content: 'create_folder',
          icon: {}
        }
      ];
    } else {
      options.value = [
        {
          type: 'upload',
          content: 'upload_files',
          icon: {}
        }
        // 暂时禁用文件夹上传功能
        // {
        //   type: 'cloud-upload',
        //   content: 'upload_folder',
        //   icon: {}
        // }
      ];
    }
  }
};

const play = ref(() => {});

const isTriggeredOptionBoardCloseHandle = ref(false);

const optionBoardCloseHandle = () => {
  isOptionBoardOpen.value = false;
  isTriggeredOptionBoardCloseHandle.value = true;
};
watch(
  () => container.value,
  () => {
    if (container.value) {
      fileStore.setContainer(container.value);
    }
  }
);

onBeforeUpdate(() => {
  play.value = fileStore.flip();
});
// onUpdated(() => {
//   nextTick(() => {
//     if (isTriggeredOptionBoardCloseHandle.value) {
//       isTriggeredOptionBoardCloseHandle.value = false;
//       return;
//     }
//     play.value();
//   });
// });

const isSelected = (item) => {
  const isSelected =
    (item.type === 'folder' &&
      fileStore.curFileInfo[FILE_LIST.FOLDER_ID] ===
        item[FILE_LIST.FOLDER_ID]) ||
    (fileStore.curFileInfo[FILE_LIST.FILE_ID] &&
      fileStore.curFileInfo[FILE_LIST.FILE_ID] === item[FILE_LIST.FILE_ID]);
  return isSelected ? 'bg-light-background dark:bg-dark-foreground' : '';
};

function selectFile(item) {
  fileStore.setCurFileInfo(item);
}

const checked = ref(false);

const selectAll = () => {
  if (checked.value) {
    fileStore.setdelFileList(renderList.value);
  } else {
    fileStore.setdelFileList([]);
  }
};

const checkeds = () => {
  if (renderList.value.length === fileStore.delFilesList.length) {
    checked.value = true;
    console.log(fileStore.delFilesList);
  } else {
    checked.value = false;
  }
};

const deleteAll = () => {
  if (path === '/trash') {
    fileStore.optimizeFunctions('Cancel').then(() => {
      fileStore.getdelFileList(0, 'trash');
    });
  } else {
    fileStore.optimizeFunctions('del').then(() => {
      fileStore.updateFileList(fileStore.curFolderId);
    });
  }
};

const recover = () => {
  fileStore.optimizeFunctions('recover').then(() => {
    fileStore.getdelFileList(0, 'trash');
  });
};

const renderList = computed(() => {
  let list = [...fileStore.curFolderList, ...fileStore.curFileList];
  if (props.mode === 'share') {
    list = fileStore.curShareList.map((s) => s.file);
  }
  return list.map((file) => {
    const isFolder = !file[FILE_LIST.FILE_ID] && file[FILE_LIST.FILE_ID] !== 0;

    if (isFolder) {
      return {
        ...file,
        type: 'folder',
        times: file[FILE_LIST.CREATE_TIME],
        items: file[FILE_LIST.FOLDER_ITEMS]
      };
    } else {
      const fileType = getFileType('.' + file[FILE_LIST.EXT]);
      const type =
        fileType.type === 'image'
          ? 'image'
          : fileType.extension === 'unknown_type'
          ? ''
          : fileType.extension;
      const size = formatFileSize(file[FILE_LIST.SIZE]);
      const times = file[FILE_LIST.CREATE_TIME];
      // const url = file[FILE_LIST.IMG_URL].replace('https', 'http')
      const url = file[FILE_LIST.IMG_URL];
      return {
        ...file,
        type,
        size,
        times,
        url,
        fileType
      };
    }
  });
});

// const uplode = (e) => {
//   for (let file of e.files) {
//     const task = upload(file, fileStore.curFolderId)
//       .then((res) => {
//         toastStore.showToast({
//           severity: 'success',
//           summary: 'Success Message',
//           detail:
//             '[' +
//             res.data.name +
//             ']' +
//             '  ' +
//             i18nStore.translate('upload_success'),
//           life: 2000,
//           group: 'upload_success'
//         });
//         setTimeout(() => {
//           toastStore.closeToastGroup('upload_success');
//         }, 3000);
//         fileStore.updateFileList(fileStore.curFolderId);
//       })
//       .catch((err) => {
//         toastStore.showToast({
//           severity: 'error',
//           summary: 'Error Message',
//           detail:
//             '[' + err.name + ']' + '  ' + i18nStore.translate('upload_failed'),
//           life: 999999,
//           group: 'upload_failed'
//         });
//       });
//     fileStore.addUploadTask(task);
//   }
// };

const uplode = (files, folderId) => {
  for (let file of files) {
    const task = upload(file, folderId)
      .then((res) => {
        toastStore.showToast({
          severity: 'success',
          summary: 'Success Message',
          detail:
            '[' +
            res.data.name +
            ']' +
            '  ' +
            i18nStore.translate('upload_success'),
          life: 2000,
          group: 'upload_success'
        });
        setTimeout(() => {
          toastStore.closeToastGroup('upload_success');
        }, 3000);
        if (fileStore.curFolderId === folderId) {
          fileStore.updateFileList(fileStore.curFolderId);
        }
      })
      .catch((err) => {
        toastStore.showToast({
          severity: 'error',
          summary: 'Error Message',
          detail:
            '[' + err.name + ']' + '  ' + i18nStore.translate('upload_failed'),
          life: 999999,
          group: 'upload_failed'
        });
      });
    fileStore.addUploadTask(task);
  }
};

const onUploader = async (e) => {
  // 判断大小文件  小文件
  if (fileStore.Type === 2) {
    // 判断是否超过300m文件 是
    if (e.files[0].size <= 314572800) {
      // 判断当前文件大小是否小于用户当前可上传大小 当前用户100M
      if (e.files[0].size <= userInfoStore.userInfo.file_size) {
        // 上传
        uplode(e.files, fileStore.curFolderId);
        return;
      } else {
        // 如果超出 提醒升级或购买空间
        toastStore.showToast({
          severity: 'error',
          summary: 'Error Message',
          detail: i18nStore.translate(
            'upgrade_to_free_version_or_buy_advanced_package'
          ),
          life: 999999,
          group: 'upload_failed'
        });
        return;
      }
    } else {
      // 判断是否超过300m文件  否
      // 弹窗提示
      toastStore.showToast({
        severity: 'error',
        summary: 'Error Message',
        detail: i18nStore.translate(
          'small_file_upload_file_size_cannot_exceed_300M'
        ),
        life: 999999,
        group: 'upload_failed'
      });
      return;
    }
  }
  // 如果是大文件
  else if (fileStore.Type === 1) {
    // 如果上传文件大小不小于剩余文件
    if (e.files[0].size <= userInfoStore.userInfo.file_space_now) {
      // 上传
      uplode(e.files, fileStore.curFolderId);
      return;
    } else {
      // 如果超出 提醒升级
      toastStore.showToast({
        severity: 'error',
        summary: 'Error Message',
        detail: i18nStore.translate(
          'insufficient_remaining_storage_space_please_upgrade_package_or_purchase_space'
        ),
        life: 999999,
        group: 'upload_failed'
      });
      return;
    }
  }
};

const dblClickHandle = (item) => {
  if (fileStore.type === 'trash') {
    return;
  }
  if (props.mode === 'share') {
    flagStore.setShareBoardOpen(true);
    return;
  }
  if (fileStore.checkIsFile(item)) {
    // 文件触发预览
    flagStore.setPreviewerOpen(true);
    fileStore.setCurFileInfo(item);
  } else if (fileStore.checkIsFolder(item)) {
    // 文件夹触发进入
    flagStore.setFileListLoading(true);
    fileStore.entryFolder(item[FILE_LIST.FOLDER_ID]).then(() => {
      flagStore.setFileListLoading(false);
    });
  }
};
//是否为网格布局，需要从pinia获取
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
